import { userBehavior } from './behavior'
import { reqUploadFile, reqUpdateUserInfo } from '@/api/user'
import { syncSetStorage } from '@/utils/storage'

Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    isShowDialog: false
  },

  async chooseAvatar(e) {
    const { avatarUrl } = e.detail
    // 将头像上传服务器
    const { data } = await reqUploadFile(avatarUrl, 'file')
    this.setData({
      'userInfo.headimgurl': data
    })
  },

  async saveUserInfo() {
    const { userInfo } = this.data
    const res = await reqUpdateUserInfo(userInfo)
    if (res.code == 200) {
      syncSetStorage('userInfo', userInfo)
      this.setUserInfo(userInfo)
      wx.switchTab({
        url: '/pages/mine/mine',
        success: () => {
          wx.toast({ title: '修改成功' })
        }
      })
    } else {
      wx.toast({ title: '修改失败，请重试' })
    }
  },
  handleUpdateNickName() {
    this.setData({
      isShowDialog: true
    })
  },
  getNickName(e) {
    const { nickname } = e.detail.value
    this.setData({
      'userInfo.nickname': nickname,
      isShowDialog: false
    })
  },
  handleCancel() {
    this.setData({
      isShowDialog: false
    })
  },
  // 生命周期函数--监听页面加载
  onLoad: function (options) {}
})
